/*
Copyright 2011 Gabriel Flores

*/
package com.asfusion.mate.extension.actions.builders
{
	import com.asfusion.mate.actionLists.IScope;
	import com.asfusion.mate.actions.IAction;
	import com.asfusion.mate.core.ISmartObject;
	
	import mx.messaging.ChannelSet;
	import mx.rpc.AsyncToken;

	public class ChannelSetLoginInvoker extends ChannelSetInvoker implements IAction
	{
		
		private var loginUsername:String;
		private var loginPassword:String;
		
		override protected function prepare(scope:IScope):void
		{
			super.prepare(scope);
		
			if(username && password)
			{
				if(username is ISmartObject)
				{
					loginUsername = ISmartObject(username).getValue(scope) as String;
				} 
				if( username is String )
				{	
					loginUsername = username as String;
				}
				if( password is ISmartObject)
				{
					loginPassword = ISmartObject(password).getValue(scope) as String;
				}
				if( password is String )
				{	
					loginPassword = password as String;
				}
			} 
			
			if( !loginUsername || !loginPassword) 
			{
				throw( new Error( "No user or password indicated for login" ) );
			}
			
		}
		
		/*-.........................................invoke..........................................*/
		/**
		 * @inheritDoc
		 */
		override protected function invoke( channelSet:ChannelSet ):AsyncToken
		{
			var localToken:AsyncToken;
			
			if( !channelSet.authenticated )
			{
				localToken = channelSet.login( loginUsername, loginPassword ); 
			} else {
				throw( new Error( "ChannelSet is already authenticated." ) );
			}
			
			return localToken;
		}
		
	}
}